package com.hjy.interceptor;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hjy.pojo.R;
import com.hjy.pojo.UserDetail;
import com.hjy.pojo.UserInfo;
import com.hjy.properties.HjySecurityProperties;
import com.hjy.utils.TokenManager;
import com.hjy.utils.UserDetailHandler;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截 login 请求
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private TokenManager tokenManager;
    private UserDetailHandler userDetailHandler;
    private StringRedisTemplate stringRedisTemplate;
    private HjySecurityProperties hjySecurityProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getRequestURI().equals(hjySecurityProperties.getLoginPath())) {
            String s = IoUtil.read(request.getInputStream(), "utf-8");
            response.setContentType("application/json;charset=utf-8");
            if (StrUtil.isBlank(s)) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error().setMessage("无法解析出用户信息, 请重试!")));
                return false;
            }
            UserInfo userInfo = JSONUtil.toBean(s, UserInfo.class);
            // 通过该 request 获取 userInfo
            if (StrUtil.isBlank(userInfo.getUsername()) || StrUtil.isBlank(userInfo.getPassword())) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error().setMessage("无法解析出用户名或者密码, 请重试!")));
                return false;
            }
            // 判断是否是正确的登录
            if (!userDetailHandler.loginCorrect(userInfo)) {
                response.getWriter().write(JSONUtil.toJsonStr(R.error().setMessage("用户名和密码不匹配, 请重试!")));
                return false;
            }
            String token = tokenManager.createToken(userInfo.getUsername());
            // 存储到redis
            UserDetail userDetail = userDetailHandler.loadUserByUsername(userInfo.getUsername());
            stringRedisTemplate.opsForValue().set(hjySecurityProperties.getRedisPrefix()+token, JSONUtil.toJsonStr(userDetail),hjySecurityProperties.getRedisDuration(), hjySecurityProperties.getRedisTimeUnit());
            response.getWriter().write(JSONUtil.toJsonStr(R.ok(token)));
            return false;
        }
        return true;
    }
}
